package org.example.aienglishapp_login.service.notification;

import lombok.extern.slf4j.Slf4j;
import org.example.aienglishapp_login.config.others.MyWebSocketHandler;
import org.example.aienglishapp_login.entity.notification.Notification;
import org.example.aienglishapp_login.mapper.notification.NotificationMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author Asus
 */
@Service
@Slf4j
public class NotificationService {

    @Autowired
    private NotificationMapper notificationMapper;

    public NotificationService(MyWebSocketHandler webSocketHandler) {
    }

    // 创建通知并保存
    @Transactional
    public void createNotification(String message) {
        Notification notification = new Notification(message);
        notificationMapper.insertNotification(notification);
        try {
            MyWebSocketHandler.sendMessageToAllClients(message);
        } catch (Exception e) {
            log.error("Error while sending message to all clients", e);
        }
    }

    // 获取所有通知
    public List<Notification> getAllNotifications() {
        return notificationMapper.getAllNotifications();
    }

    // 获取未读通知
    public List<Notification> getUnreadNotifications() {
        return notificationMapper.getUnreadNotifications();
    }

    // 标记通知为已读
    public void markNotificationAsRead(Long notificationId) {
        notificationMapper.markAsRead(notificationId);
    }
}
